package com.duan.common.utils;


import com.duan.common.beans.vo.ShowModel;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.ArrayType;
import com.fasterxml.jackson.databind.type.CollectionType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * json 格式化工具
 */
public abstract class JsonUtil {


    private static Logger logger = LoggerFactory.getLogger(JsonUtil.class);

    private static ObjectMapper objectMapper = new ObjectMapper();

    static {
        //表示转换的时候，如果对象中不存在该属性，不报错
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        //表示 json 解析的时候 json字符串 是否可以使用单引号
        objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
    }


    public static String objectToString(Object obj) {

        try {
            return obj == null ? null : objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            logger.error("JsonUtil.objectToString execute fail", e);
        }
        return null;
    }


    public static <T> T stringToObject(String jsonStr, Class<T> cls) {
        try {
            return objectMapper.readValue(jsonStr, cls);
        } catch (IOException e) {
            logger.error("JsonUtil.stringToObject execute fail", e);
        }
        return null;
    }

    public static <T>List<T> stringToList(String jsonStr, Class<T> cls) {

        try {
//            return objectMapper.readValue(jsonStr, new TypeReference<List<T>>(){});
            CollectionType at = objectMapper.getTypeFactory().constructCollectionType(ArrayList.class, cls);
            return objectMapper.readValue(jsonStr, at);
        } catch (IOException e) {
            logger.error("JsonUtil.stringToList execute fail", e);
        }
        return new ArrayList<>();
    }


//    public static void main(String[] args) {
//
//
//        ShowModel showModel = new ShowModel();
//        showModel.setName("12312312");
//        showModel.setId(11);
//
//        System.out.println(objectToString(showModel));
//
//        String str = "{\"id\":11,\"name\":\"12312312\"}";
//        System.out.println(stringToObject(str, ShowModel.class));
//
//        str = "[{\"id\":11,\"name\":\"12312312\"}]";
//        System.out.println(stringToList(str, ShowModel.class));
//    }

}
